/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.sys.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.bean.app.param.ShopUserRegisterParam;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.impl.VerificationCodeService;
import com.yami.shop.sys.comment.dao.ShopEmployeeMapper;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.service.ShopUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 商家用户服务实现类
 * 
 * @author lhd
 * @date 2023-03-11
 */
@Service
@AllArgsConstructor
@Slf4j
public class ShopUserServiceImpl implements ShopUserService {
    
    private final ShopEmployeeMapper shopEmployeeMapper;
    private final ShopDetailService shopDetailService;
    private final PasswordEncoder passwordEncoder;
    private final VerificationCodeService verificationCodeService;
    
    /**
     * 商家用户注册
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(ShopUserRegisterParam registerParam) {
        // 1. 校验密码是否一致
        if (!registerParam.getPassword().equals(registerParam.getConfirmPassword())) {
            throw new YamiShopBindException("yami.shop.user.password.not.match");
        }
        
        String username = registerParam.getUsername();
        
        // 2. 根据注册类型处理用户名和验证码
        String email = null;
        String mobile = null;
        
        if (registerParam.getRegisterType() == 0) {
            // 邮箱注册
            if (!PrincipalUtil.isEmail(username)) {
                throw new YamiShopBindException("yami.email.format.error");
            }
            email = username;
            // 验证邮箱验证码
            boolean isValid = verificationCodeService.verifyCode(email, registerParam.getVerificationCode());
            if (!isValid) {
                throw new YamiShopBindException("yami.shop.user.verification.code.error");
            }
        } else {
            // 手机号注册
            if (!PrincipalUtil.isMobile(username)) {
                throw new YamiShopBindException("yami.mobile.format.error");
            }
            mobile = username;
            // 验证手机验证码
            boolean isValid = verificationCodeService.verifyCode(mobile, registerParam.getVerificationCode());
            if (!isValid) {
                throw new YamiShopBindException("yami.shop.user.verification.code.error");
            }
        }
        
        // 3. 检查用户名是否已存在
        if (checkUsernameExists(username)) {
            throw new YamiShopBindException("yami.shop.user.username.exists");
        }
        
        // 4. 计算新的shopId (shopEmployee数据个数+1)
        Long shopId = generateShopId();
        
        // 5. 创建商家用户
        ShopEmployee shopEmployee = new ShopEmployee();
        shopEmployee.setUsername(username);
        shopEmployee.setPassword(passwordEncoder.encode(registerParam.getPassword()));
        shopEmployee.setEmail(email);
        shopEmployee.setMobile(mobile);
        shopEmployee.setStatus(1); // 正常状态
        shopEmployee.setType(1); // 普通员工
        shopEmployee.setCreateTime(new Date());
        shopEmployee.setShopId(shopId); // 设置shopId

        ShopDetail shopDetail = new ShopDetail();
        shopDetail.setShopId(shopId);
        shopDetail.setEmail(email);
        shopDetail.setMobile(mobile);
        shopDetail.setCreateTime(new Date());
        shopDetail.setPassword(passwordEncoder.encode(registerParam.getPassword()));
        // 6. 保存商家用户
        int result = shopEmployeeMapper.insert(shopEmployee);
        
        return result > 0;
    }
    
    /**
     * 验证用户名是否存在
     */
    @Override
    public boolean checkUsernameExists(String username) {
        ShopEmployee existEmployee = shopEmployeeMapper.getShopByMobileOrEmail(username);
        return existEmployee != null;
    }
    
    /**
     * 验证店铺ID是否存在
     */
    @Override
    public boolean checkShopIdExists(Long shopId) {
        QueryWrapper<ShopEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        Integer count = shopEmployeeMapper.selectCount(queryWrapper);
        return count > 0;
    }
    
    /**
     * 生成新的shopId (shopEmployee数据个数+1)
     */
    private Long generateShopId() {
        Integer count = shopEmployeeMapper.selectCount(null);
        return count.longValue() + 1;
    }
} 